﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using StockFinder.Model;

namespace StockFinder.Services.Extractors.Nasdaq
{
    /// <summary>
    /// Downloads Symbols list from the NASDAQ stock exchange
    /// </summary>
    public class NasdaqSymbolExtractor : ISymbolListExtractor
    {
        private const string INDEXURL = "http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download";
                
        public List<Symbol> GetSymbolList()
        {
            List<Symbol> symbols = new List<Symbol>();

            //create webrequest from url
            HttpWebRequest webRequest = HttpWebRequest.Create(INDEXURL) as HttpWebRequest;

            HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;

            string pageSource = null;

            //create the reader to extract the page source
            using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream()))
            {                
                //get the page source
                pageSource = streamReader.ReadToEnd();
            }

            if (string.IsNullOrEmpty(pageSource))
            {

            }
            else
            {
                string[] lines = pageSource.Split(new char[] { Environment.NewLine.ToCharArray()[0] });

                foreach (string line in lines)
                {
                    string[] fields = line.Split(new char[] { ',' });

                    try
                    {

                    }
                    catch (Exception exception)
                    {
                        string symbol = fields[0];
                        throw;
                    }                    
                }                                    
            }

            webResponse = null;
            webRequest = null;

            return symbols;
        }
    }
}
